/**
 * 
 */
package org.dragonfire.editor.z80.hiliteRules;

import org.dragonfire.editor.syntax.rules.LineReturnRule;
import org.dragonfire.editor.z80.AssemblyScanner;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;

/**
 * @author Darth Android
 * @date Oct 2, 2007
 */
public class FunctionRule implements IRule {

	public static final String FUNCTION_START_CHAR = "$";
	private IToken token;

	public FunctionRule(IToken token) {
		this.token = token;
	}

	public IToken evaluate(ICharacterScanner scanner) {
		if (!(scanner instanceof AssemblyScanner))
			return Token.UNDEFINED;
		AssemblyScanner scan = (AssemblyScanner) scanner;
		if (scan.getLastMatchedRule() == null || scan.getLastMatchedRule() instanceof LineReturnRule)
			return Token.UNDEFINED;
		return evaluate(scanner, false);
	}

	public IToken evaluate(ICharacterScanner scanner, boolean seenText) {
		char c = (char) scanner.read();
		if (c == ICharacterScanner.EOF && !seenText) {
			scanner.unread();
			return Token.UNDEFINED;
		}
		IToken t = Token.UNDEFINED;
		if (Character.isWhitespace(c) && !seenText)
			t = evaluate(scanner, false);
		if (seenText) {
			if ("abcdefghijklmnopqrstuvwxyz0123456789_.".contains("" + Character.toLowerCase(c)))
				t = evaluate(scanner, true);
			else {
				scanner.unread();
				t = token;
			}
		}
		else if (FUNCTION_START_CHAR.contains("" + c))
			t = evaluate(scanner, true);
		if (t == Token.UNDEFINED)
			scanner.unread();
		return t;
	}
}
